const dStoreService = require('./../services/dStoreService');
const request = require('request');

const phoneVscodeCache = {

}

module.exports = {
    async getAllStoreList(ctx){
        let result = await dStoreService.getAllStoreList();
        ctx.body = result;
    },

    async index(ctx){
        await ctx.render('index')
    },

    async getBannerList(ctx){
        let result = await dStoreService.getBannerList();
        ctx.body = result;
    },

    async getTodayList(ctx){
        let result = await dStoreService.getTodayList();
        ctx.body = result;
    },

    async login(ctx){
        let param = ctx.request.body;
        let code = param.code;
        let phone = param.phone;

        if(phoneVscodeCache[phone] === code) {
            let userId = await dStoreService.getUserId(phone);
            ctx.body = {
                result: true,
                content: userId
            }
        }else {
            ctx.body = {
                result: false,
                content: '验证码不正确'
            }
        }
    },

    async sendVcode(ctx) {
        let param = ctx.request.body;
        let phone = param.phone;
        let code = getCode();
        phoneVscodeCache[phone] = code;
        let content = `【人人易贷】验证码:${code}`
        request.post( "http://101.227.68.68:7891/mt", {
            form: {
                    un: "811685",
                    pw: "RRD236j",
                    dc: "15",
                    rd: "1",
                    tf: "3",
                    da: phone,
                    sm: content
                }
            });
        ctx.body = 'success'
    },

    async getRecentDateList(ctx){
        let result = await dStoreService.getRecentDateList();
        ctx.body = result;
    },

    async getDateItem(ctx){
        let param = ctx.query;
        let result = await dStoreService.getDateItem(param.date);
        ctx.body = result;
    },
    
    async getItemByKeyword(ctx){
        let param = ctx.query;
        let result = await dStoreService.getItemByKeyword(param.keyword);
        ctx.body = result;
    }
};

function getCode() {
    var num="";
    for(var i=0;i<4;i++){
        num+=Math.floor(Math.random()*10)
    }
    return num
}
